package org.jradweb.core.taglib;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;

import javax.servlet.jsp.JspException;

import org.apache.commons.beanutils.BeanUtils;

/**
 * &lt;j:list items="${items}" property="id" separator=","/&gt; outputs:
 * ${item.id},${item.id},${item.id},
 * 
 * if property is null , ${item} would be writer to page default separator is
 * "," Created On May 12, 2008
 * 
 * @author <a href="mailto:wagzhi@gmail.com">Paul Wang</a>
 * @version $Id: CollectionListTag.java 149 2008-10-10 03:10:10Z wagzhi $
 */
public class CollectionListTag extends BaseTag {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2932616435755144088L;

	private String separator = ",";
	private Collection items;
	private String property;

	public String getSeparator() {
		return separator;
	}

	public void setSeparator(String separator) {
		this.separator = separator;
	}

	public Collection getItems() {
		return items;
	}

	public void setItems(Collection items) {
		this.items = items;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	@Override
	public int doEndTag() throws JspException {
		if(items==null)
		{
			return super.doEndTag();
		}
		try {
			boolean isFirst = true;
			for (Object item : items) {
				if (!isFirst) {
					this.pageContext.getOut().write(this.separator);
				}
				if (this.property == null) {
					this.pageContext.getOut().write(item.toString());
				} else {
					String value = BeanUtils.getProperty(item, property);
					this.pageContext.getOut().write(value);
				}
				isFirst=false;
			}
			return super.doEndTag();
		} catch (IOException e) {
			throw new JspException(e);
		} catch (IllegalAccessException e) {
			throw new JspException(e);
		} catch (InvocationTargetException e) {
			throw new JspException(e);
		} catch (NoSuchMethodException e) {
			throw new JspException(e);
		}
	}

}
